layui.use(['form', 'layer', 'table'], function () {
	var form = layui.form,
		layer = parent.layer === undefined ? layui.layer : top.layer,
		$ = layui.jquery,
		table = layui.table,
		company_id = sessionStorage["company_id"],
		user_id = sessionStorage["userId"],
		scale = sessionStorage["scale"];
	if (user_id == 3) {
		loadCompanyList(form, $);
		$('.company').removeClass("layui-hide");
	}
	//渲染下拉框数据
	$('.companyName').append(getCompanyNameList())
	loadSelect(form, $, "educationType/getEducationType.php", ".projectType")
	form.render('select')
	//项目信息列表
	var tableIns = table.render({
		elem: '#projectList',
		url: baseUrl + 'project_info/getProjects.php',
		where: {
			company_id
		},
		skin: 'row',
		even: true, //开启隔行背景
		toolbar: true,
		defaultToolbar: ['filter'],
		cellMinWidth: 95,
		page: true,
		limits: [10, 15, 20, 25],
		limit: 10,
		id: "projectListTable",
		cols: [
			[{
				title: '序号',
				type: "numbers",
				align: "center"
			},
			{
				field: 'Id',
				title: 'ID',
				align: "center",
				hide: true
			},
			{
				field: 'produ',
				title: '项目名称',
				align: "center"
			},
			{
				field: 'companyName',
				title: '合作公司',
				align: "center",
				templet: function (d) {
					if (scale == "1") {
						return '<span style="color: #e4393c;">' + d.companyName + '</span>';
					} else {
						return '<span style="color: #e4393c;">' + "北京博烨教育科技有限公司" + '</span>';
					}
				}
			}, {
				field: 'produIntroduce',
				title: '项目详情',
				align: "center"
			}, {
				field: 'price',
				title: '合作价格',
				align: "center",
				hide: true,
				templet: function (d) {
					if (scale >= 3) {
						return '<span style="color: #e4393c;">' + "0" + '</span>';
					} else if (scale == "2" || scale == "1") {
						return '<span style="color: #e4393c;">' + d.price + '</span>';
					}

				}
			}, {
				field: 'Agencyprice',
				title: '代理价格',
				align: "center",
				hide: false,
				templet: function (d) {

					if (scale < "5") {
						return '<span style="color: #e4393c;">' + d.Agencyprice + '</span>';
					}
					else {
						return '<span style="color: #e4393c;">' + "0" + '</span>';

					}

				}

			}, {
				field: 'Externalprice',
				title: '价格',
				align: "center"
			}, {
				field: 'remarks',
				title: '备注',
				align: "center"
			}, {
				field: 'type',
				title: '项目类型ID',
				align: "center",
				hide: true
			}, {
				field: 'educationtype_name',
				title: '项目类型',
				align: "center",
				templet: function (d) {
					return `<span style="color: #e4393c;">${d.educationtype_name}</span>`;
				}
			}, {
				field: 'validYear',
				title: '适用年份',
				align: "center"
			}, {
				title: '操作',
				width: 150,
				templet: '#projectListBar',
				fixed: "right",
				align: "center"
			}
			]
		],
		done: function (res, curr, count) { // done 数据表格加载完成
			//合作公司和添加项目  显示和隐藏
			if (sessionStorage['scale'] == 1 || sessionStorage['scale'] == 2) {
				$('.addNews_btn').css('display', '')
				$('.gongsiname').css('display', '')
			}
			else {
				$('.addNews_btn').css('display', 'none')
				$('.gongsiname').css('display', 'none')
			}
		}
	});
	$('.searchProjectName').on('keyup', function (event) {
		if (event.keyCode != 13) return
		$(".search_btn").click()
	})
	//搜索
	$(".search_btn").on("click", function () {
		table.reload("projectListTable", {
			page: {
				curr: 1 //重新从第 1 页开始
			},
			where: {
				rponame: $('.searchProjectName').val(),
				typeLo: $('.companyName').val(),
				typephj: $('.projectType').val(),
				company_id: user_id == 3 ? $("#company").val() : company_id
			}
		})
	});
	//添加项目信息
	function editProject(edit) {
		var index = layui.layer.open({
			title: "编辑项目信息",
			type: 2,
			area: ['80%', '80%'],
			fixed: false, //不固定
			maxmin: true,
			shadeClose: true,
			content: "projectEdit.html",
			success: async function (layero, index) {
				var body = layui.layer.getChildFrame('body', index);
				//渲染模态框中下拉框数据
				(await loadSelect(form, $, 'educationType/getEducationType.php', '', 'edit')).forEach(item => {
					if (index != 0) body.find('.educationType').append(new Option(item.name, item.id))
				});
				body.find(".companyName").append(getCompanyNameList())
				if (edit) { //修改
					body.find(".addOrUpdate").val(1);
					body.find(".projectId").val(edit.Id);
					body.find(".projectName").val(edit.produ);
					body.find(".projectDetail").val(edit.produIntroduce);
					body.find(".price").val(edit.price);
					body.find(".agencyPrice").val(edit.Agencyprice);
					body.find(".externalPrice").val(edit.Externalprice);
					body.find(".remarks").val(edit.remarks);
					body.find(".educationType").val(edit.type);
					body.find(".companyName").val(edit.rid);
					body.find(".validYear").val(edit.validYear);
				} else { //添加
					body.find(".addOrUpdate").val(0);
				}
				setTimeout(function () {
					layui.layer.tips('点击此处返回项目列表', '.layui-layer-setwin .layui-layer-close', {
						tips: 3
					});
				}, 500)
			}
		})
		//layui.layer.full(index);
		sessionStorage.setItem("index", index);
		//改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
	}
	$(".addNews_btn").click(function () {
		editProject();
	})
	//列表操作
	table.on('tool(projectList)', function (obj) {
		var layEvent = obj.event,
			data = obj.data;
		if (layEvent === 'edit') { //编辑
			editProject(data);
		} else if (layEvent === 'del') { //删除
			layer.confirm('确定删除项目信息 ' + data.produ + ' ？', {
				icon: 3,
				title: '删除确认'
			}, function (index) {
				$.ajax({
					url: baseUrl + "project_info/deleteProject.php",
					data: {
						id: data.Id
					},
					type: "POST",
					dataType: "text",
					success: function (data) {
						if (data == "1") {
							tableIns.reload();
							layer.close(index);
							layer.msg('删除项目信息成功！')
						} else {
							layer.msg('删除项目信息失败！')
						}
					}
				})
			});
		}
	});

	table.on('rowDouble(projectList)', function (obj) {
		editProject(obj.data);
	});

	function getCompanyNameList() {
		let str = ``;
		$.ajax({
			url: baseUrl + "project_info/getCompanyName.php",
			data: {
				company_id
			},
			type: "GET",
			async: false,
			dataType: "JSON",
			success: function (data) {
				if (data) {
					data.forEach(function (item) {
						str += `<option value="${item.Id}">${item.companyName}</option>`
					})
				}
			}
		})
		return str;
	}
})